<template>
    <el-container class="print_item_container">
        <vAside ref="printItemAside"
                :options="asideOptions"
                :treeOptions="treeOptions"
                :treeData="treeData"
                is-show-header
                @event="handleAsideEvent"
                style="height: 100%">
            <template slot="button">
                <el-tooltip class="item" effect="dark" content="刷新" placement="top">
                    <i class="ml10 fa fa-refresh" @click="initTreeData()" />
                </el-tooltip>
            </template>
        </vAside>
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent" />
                <div class="card_container">
                    <vxe-table-template :data="dataList" :options.sync="tableOptions"
                                        @event="handleTableEvent" />
                </div>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import ItemForm from "../dialog/print/ItemForm";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "item",
    provide() {
        return {
            setChildrenRef: (name, ref) => {
                this[name] = ref;
            },
            getChildrenRef: (name) => {
                return this[name];
            },
            getRef: () => {
                return this;
            },
        };
    },
    data() {
        const _this = this;
        return {
            asideOptions: {
                width: '150px',
                title: '配置项组',
            },
            treeOptions: {
                ref: "$PrintGroupTree",
                highlightCurrent: true,
                defaultExpandAll: true,
                nodeKey: 'sid',
                props: {
                    label: "name",
                    children: "children",
                },
                buttons: [
                    {
                        icon: "el-icon-circle-plus-outline",
                        filter(data) {
                            return data.level === 1;
                        },
                        method: (data, $event) => {
                            _this.openGroupDialog(data, 'add');
                        },
                    },
                    {
                        icon: "fa fa-pencil",
                        filter(data) {
                            return data.level !== 1;
                        },
                        method: (data, $event) => {
                            _this.openGroupDialog(data, 'edit');
                        },
                    },
                    {
                        icon: "fa fa-trash-o",
                        filter(data) {
                            return data.level !== 1;
                        },
                        method: (data, $event) => {
                            _this.deleteConfirm(data, true);
                        },
                    },
                ],
            },
            treeData: [],
            treeNodeKey: {},
            searchForm: {},
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList();
                        },
                    },
                    {
                        id: "add",
                        icon: "fa fa-plus",
                        type: "primary",
                        show: true,
                        method: () => {
                            _this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: "edit",
                        icon: "fa fa-pencil",
                        type: "success",
                        show: true,
                        method: () => {
                            _this.openDialog(null, 'edit');
                        },
                    },
                    {
                        id: "delete",
                        icon: "fa fa-trash-o",
                        type: "danger",
                        show: true,
                        method: () => {
                            _this.deleteConfirm();
                        },
                    },
                ],
            },
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: "PrintItemTable",
                container: ".print_item_container",
                multiSelect: true,
                columns: [
                    {
                        label: "归属功能",
                        prop: "type",
                        align: "center",
                        width: 120,
                        formatter: (row) => {
                            let filter = _this.printTypeList.filter(item => item.value === row.type);
                            if (_this.$utils.isNotEmptyList(filter)) {
                                return filter[0].display_text;
                            }
                            return '';
                        },
                    },
                    {
                        label: "配置项组",
                        prop: "parent_name",
                        align: "center",
                        width: 120,
                    },
                    {
                        label: "配置项名称",
                        prop: "name",
                        align: "center",
                    },
                    {
                        label: "配置项字段",
                        prop: "code",
                        align: "center",
                    },
                    {
                        label: "配置项类型",
                        prop: "cfg_type",
                        align: "center",
                        formatter(row) {
                            let filter = _this.cfgTypeList.filter(item => item.value === row.cfg_type);
                            if (_this.$utils.isNotEmptyList(filter)) {
                                return filter[0].label;
                            }
                            return '';
                        },
                    },
                    {
                        label: "状态",
                        prop: "state",
                        align: "center",
                        width: 100,
                        cellRender: {
                            name: 'ElSwitch',
                            props: {
                                activeValue: 1,
                                inactiveValue: 0,
                            },
                            events: {
                                change: _this.saveRow,
                            },
                        },
                    },
                    {
                        label: "排序",
                        prop: "sn",
                        align: "center",
                        width: 100,
                    },
                ],
                operates: {
                    list: [
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            type: "primary",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "编辑",
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'edit');
                            },
                        },
                        {
                            id: "delete",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "删除",
                            },
                            method: (index, row) => {
                                _this.deleteConfirm(row);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
        };
    },
    computed: {
        ...mapState('base', ['printTypeList', 'cfgTypeList']),
        type() {
            return this.$route.params.type;
        },
    },
    mounted() {
        this.init();
    },
    methods: {
        handleAsideEvent(event) {
            if (event.type === "nodeClick") {
                this.treeNodeKey = event.data;
                this.getList(true);
            }
        },
        handleHeaderEvent(event) {
            this.searchForm = $.extend({}, this.searchForm, event.searchForm);
            if (event.type === "search") {
                this.getList();
            } else if (event.type === "refresh") {
                this.getList();
            }
        },
        async init() {
            const _this = this;
            _this.treeNodeKey = {};
            if (!_this.$utils.isNotEmptyList(this.printTypeList)) {
                await _this.$store.dispatch('base/initPrintTypeList');
            }
            await _this.initTreeData();
            if (_this.$utils.isNotEmpty(_this.treeNodeKey.sid)) {
                _this.getList(true);
            }
        },
        initTreeData() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindBasePrintDesignItems, {
                cfg_type: 'group',
                nopage: '1',
            }).then(result => {
                _this.resetTreeData(result.data);
            }).catch(() => {
            });
        },
        resetTreeData(datas) {
            const _this = this;
            let list = [];
            let filter = _this.printTypeList.map(item => $.extend({}, item));
            if (_this.$utils.isNotEmpty(_this.type)) {
                filter = filter.filter(item => item.value === _this.type);
            }
            filter.forEach(item => {
                let obj = {
                    sid: item.sid,
                    type: item.value,
                    name: item.display_text,
                    level: 1,
                };
                let filter = (datas || []).filter(t => t.type === item.value);
                if (_this.$utils.isNotEmptyList(filter)) {
                    obj.children = filter.map(t => {
                        let obj = $.extend({}, t);
                        obj.level = 2;
                        obj.cfg_group_sid = t.sid;
                        return obj;
                    });
                }
                list.push(obj);
            });
            _this.treeData = list;
            if (!_this.$utils.isNotEmpty(_this.treeNodeKey.sid)) {
                let filter = (datas || []).filter(item => item.sid === _this.treeNodeKey.sid);
                if (!_this.$utils.isNotEmptyList(filter)) {
                    filter = list.filter(item => item.type === _this.treeNodeKey.type);
                }
                if (!_this.$utils.isNotEmptyList(filter)) {
                    filter = list.map(item => $.extend({}, item));
                }
                _this.treeNodeKey = $.extend({}, filter[0]);
            }
            _this.$nextTick(() => {
                _this.$PrintGroupTree.setCurrentKey(_this.treeNodeKey.sid);
            });
        },
        getList(search) {
            const _this = this;
            _this.dataList = [];
            if (search) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            queryData.skip_group = '1';
            if (_this.$utils.isNotEmpty(_this.treeNodeKey.type)) {
                queryData.type = _this.treeNodeKey.type;
            }
            if (_this.$utils.isNotEmpty(_this.treeNodeKey.cfg_group_sid)) {
                queryData.parent_sid = _this.treeNodeKey.cfg_group_sid;
            }
            _this.fetchData(_this.$api.API_FindBasePrintDesignItems, queryData).then(result => {
                _this.dataList = result.data || [];
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        saveRow({ row }) {
            const _this = this;
            let subData = $.extend({}, row);
            _this.fetchData(_this.$api.API_SaveBasePrintDesignItem, subData).then(() => {
                _this.$message.success('保存成功！');
            }).catch(() => {
            });
        },
        openGroupDialog(row, type) {
            const _this = this;
            let title = type === 'add' ? '创建' : '编辑';
            if (type === 'add') {
                row = {
                    type: _this.treeNodeKey.type,
                    parent_sid: _this.$utils.isNotEmpty(_this.treeNodeKey.cfg_group_sid) ? _this.treeNodeKey.cfg_group_sid : '-1',
                    cfg_type: 'group',
                };
            }
            _this.$dialog({
                title,
                width: '400px',
                component: {
                    value: ItemForm,
                    props: {
                        row,
                        isGroup: true,
                    },
                },
                confirmed() {
                    _this.initTreeData();
                },
            });
        },
        openDialog(row, type) {
            const _this = this;
            let title = type === 'add' ? '创建' : '编辑';
            let groupList = [];
            let filter = _this.treeData.filter(item => item.type === _this.treeNodeKey.type);
            if (_this.$utils.isNotEmptyList(filter)) {
                groupList = (filter[0].children || []).map(item => $.extend({}, item));
            }
            if (type === 'add') {
                row = {
                    type: _this.treeNodeKey.type,
                    parent_sid: _this.$utils.isNotEmpty(_this.treeNodeKey.cfg_group_sid) ? _this.treeNodeKey.cfg_group_sid : '',
                };
            }
            if (type === 'edit' && !row) {
                if (!_this.checkSelection(_this.selectionList)) {
                    return;
                }
                row = $.extend({}, _this.selectionList[0]);
            }
            _this.$dialog({
                title,
                width: '600px',
                component: {
                    value: ItemForm,
                    props: {
                        row,
                        groupList,
                    },
                },
                confirmed() {
                    _this.getList();
                },
            });
        },
        //删除
        deleteConfirm(row, isGroup) {
            const _this = this;
            let sids = [];
            if (row) {
                sids.push(row.sid);
            } else {
                if (!_this.checkSelection(_this.selectionList)) {
                    return;
                }
                sids = _this.selectionList.map(item => item.sid);
            }
            _this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                _this.fetchData(_this.$api.API_DeleteBasePrintDesignItems, {
                    sids
                }).then(() => {
                    _this.$message.success("删除成功");
                    if (isGroup) {
                        _this.initTreeData();
                    } else {
                        _this.getList();
                    }
                }).catch(() => {
                });
            }).catch(() => {
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.print_item_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
</style>
